package com.migrate.module.lock;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 滚动上锁服务对象
 *
 * @author zhonghuashishan
 */
public class ScrollLock implements java.io.Serializable{


    private static final long serialVersionUID = -1753559665314067716L;

    List<Scroll> scrollList =  new ArrayList<>();


    /**
     * 针对一个库的一个表的滚动处理进行上锁
     * @param tableName 表名
     * @return 上锁结果
     */
    public boolean lock(String tableName,String domain) {
        for (Scroll scroll : scrollList){
            if (scroll.getTableName().equals(tableName) && scroll.getDomain().equals(domain)){
                 return scroll.getLock().tryLock();
            }
        }
        synchronized (ScrollLock.class){
            for (Scroll scroll : scrollList){
                if (scroll.getTableName().equals(tableName) && scroll.getDomain().equals(domain)){
                    return scroll.getLock().tryLock();
                }
            }
            Scroll scroll1 = new Scroll();
            scroll1.setTableName(tableName);
            scroll1.setDomain(domain);
            scrollList.add(scroll1);
            return scroll1.getLock().tryLock();
        }
    }



    /**
     * 解锁
     * @param tableName 表名
     */
    public void unlock(String tableName,String domain){
        for (Scroll scroll : scrollList){
            if (scroll.getTableName().equals(tableName) && scroll.getDomain().equals(domain)){
                scroll.getLock().unlock();
            }
        }
    }

    /**
     * 锁对象
     */
    @Data
    static class Scroll{
        /**
         * 系统对象
         */
        private String domain;
        /**
         * 表名
         */
        private String tableName;
        /**
         * 锁
         */
        private Lock lock = new ReentrantLock(false);
    }
}
